import json
from abc import ABC, abstractmethod
from enum import Enum
import pprint

accessKeyID = "" #os.getenv("AccessKeyID")
accessKey = "" #os.getenv("AccessKey")
    
class CloudServiceProviderCategory(Enum):
    ALIYUN = 1
    TENCENT = 2
    AZURE = 3
    
class CloudServiceProvider(ABC):
    @abstractmethod
    def listVMs(self):
        pass
    
    @abstractmethod
    def listRDS(self):
        pass
    
#阿里云
from aliyunsdkcore.client import AcsClient
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
from aliyunsdkrds.request.v20140815 import DescribeDBInstancesRequest

class AliyunProvider(CloudServiceProvider):
  def __init__(self):
    #client = AcsClient( 'cn-hangzhou')      
    self.client = AcsClient(accessKeyID, accessKey, 'cn-beijing')
    
  def listVMs(self):            
    request = DescribeInstancesRequest.DescribeInstancesRequest()
    response = self.client.do_action_with_exception(request)
    
    response_data = json.loads(response.decode('utf-8'))
    #pprint.pprint(response_data)
    print(json.dumps(response_data, indent=1, ensure_ascii=False))
    
  def listRDS(self):
    request = DescribeDBInstancesRequest.DescribeDBInstancesRequest()
    request.set_accept_format('json')

    response = self.client.do_action_with_exception(request)
    response_dict = json.loads(response)

    # 打印RDS实例列表
    for instance in response_dict['Items']['DBInstance']:
        print(f"Instance ID: {instance['DBInstanceId']}")
        print(f"Instance Description: {instance.get('DBInstanceDescription', 'N/A')}")
        print(f"Engine: {instance['Engine']}")
        print(f"Region: {instance['RegionId']}")
        print("--------")
#
from tencentcloud.common import credential
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from tencentcloud.cvm.v20170312 import cvm_client, rds_client
from tencentcloud.cvm.v20170312 import models

class TencentCloudProvider(CloudServiceProvider):
  def listVMs(self):
    cred = credential.Credential("<your-secret-id>", "<your-secret-key>")
    httpProfile = HttpProfile()
    httpProfile.endpoint = "cvm.tencentcloudapi.com"
    clientProfile = ClientProfile()
    clientProfile.httpProfile = httpProfile
    client = cvm_client.CvmClient(cred, "", clientProfile)
    req = models.DescribeInstancesRequest()
    resp = client.DescribeInstances(req)
    print(resp.to_json_string())
    
  def listRDS(self):
    cred = credential.Credential(secret_id, secret_key)

    # 创建HTTP和客户端配置
    http_profile = HttpProfile()
    http_profile.endpoint = "rds.tencentcloudapi.com"

    client_profile = ClientProfile()
    client_profile.httpProfile = http_profile

    # 实例化RDS客户端
    client = rds_client.RdsClient(cred, region, client_profile)      
    req = models.DescribeDBInstancesRequest()
    resp = client.DescribeDBInstances(req)
    if resp.TotalCount > 0:
        for instance in resp.Items:
            print(f"Instance ID: {instance.InstanceId}")
            print(f"Instance Name: {instance.InstanceName}")
            print(f"Region: {instance.Region}")
            print(f"Status: {instance.Status}")
            print("--------")
    else:
        print("No RDS instances found.")
        
#
from azure.identity import DefaultAzureCredential
from azure.mgmt.compute import ComputeManagementClient

class AzureProvider(CloudServiceProvider):
  def listVMs(self):
    credential = DefaultAzureCredential()
    subscription_id = "<your-subscription-id>"
    compute_client = ComputeManagementClient(credential, subscription_id)

    for vm in compute_client.virtual_machines.list_all():
        print(vm.name)
        
class CloudServiceProviderFactory:
    @staticmethod
    def get_provider(provider_type):
        if provider_type == CloudServiceProviderCategory.ALIYUN:
            return AliyunProvider()
        elif provider_type == CloudServiceProviderCategory.TENCENT:
            return TencentCloudProvider()
        elif provider_type == CloudServiceProviderCategory.AZURE:
            return AzureProvider()

from dotenv import load_dotenv
import os
if __name__ == "__main__":  
    load_dotenv('./.env')
    accessKeyID = os.getenv("AccessKeyID")
    accessKey = os.getenv("AccessKey")
    if (accessKeyID is not None and accessKeyID.strip()) and (accessKey is not None and accessKey.strip()):
        print(f'AccessKeyID: {accessKeyID}')
    else:
        print("API Key is either None or empty.")
        exit(1)
        
    provider = CloudServiceProviderFactory.get_provider(CloudServiceProviderCategory.ALIYUN)
    provider.listVMs()
    